<template>
  <div class="course-profile">

    <div class="course-profile__header">
      <el-button type="primary" @click="handleOpenDialog">上传附件</el-button>
      <el-button
        type="danger"
        :disabled="current.length <= 0"
        @click="batchDelete"
      >
        批量删除
      </el-button>
    </div>

    <el-table
      ref="elTableRef"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column prop="title" label="附件名称" align="center" />
      <el-table-column prop="cover" label="附件封面" align="center">
        <template v-slot="{ row }">
          <el-image :src="row.cover" style="width: 50px;height: 50px;" fit="cover">
            <div slot="error">
              <div class="image-slot">
                <i class="el-icon-picture-outline" />
              </div>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="{ row }">
          <el-button type="text" @click="download(row)">下载</el-button>

          <el-button
            type="text"
            style="color: #FF4949;"
            @click="deleteFile(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :visible.sync="visible"
      title="上传附件"
      append-to-body
    >
      <el-form
        ref="elFormRef"
        :model="form"
        label-position="left"
        label-width="auto"
        :rules="rules"
      >

        <el-form-item prop="title" label="附件名称">
          <el-input v-model="form.title" placeholder="请输入附件名称" />
        </el-form-item>

        <el-form-item prop="file" label="附件上传">
          <el-upload
            ref="fileUploadRef"
            class="upload-demo"
            drag
            action="/api/v1/upload/file"
            multiple
            :limit="1"
            :on-success="(e) => uploadSuccess(e, 'file')"
            :accept="accept"
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>

        <el-form-item prop="cover" label="封面">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            action="/api/v1/upload/file"
            :show-file-list="false"
            :on-success="(e) => uploadSuccess(e, 'cover')"
            accept=".jpg,.jpeg,.png"
          >
            <img v-if="form.cover" :src="form.cover" class="avatar" alt="封面">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

      </el-form>

      <div slot="footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="addFileToCourse">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { getCourseProfile, addFileToCourse, deleteFileToCourse } from '@/api/v2/course'
import { isArray } from '@/utils/kris_utils'
export default {
  name: '',
  data() {
    return {
      list: [],
      courseId: null,
      loading: false,
      visible: false,
      form: {
        title: '',
        file: '',
        cover: ''
      },
      rules: {
        title: [{ required: true, message: '附件名称不能为空', trigger: ['blur', 'change'] }],
        file: [{ required: true, message: '请上传附件', trigger: ['blur', 'change'] }]
      },
      current: [],
      accept: '.jpg,.jpeg,.png,.doc,.docx,.xls,.xlsx,.pdf,.pptx,.ppt'
    }
  },
  created() {
    const { params } = this.$route
    this.courseId = params.id / 1
    this.init()
  },
  methods: {

    handleOpenDialog() {
      this.visible = true
      this.$nextTick(() => {
        this.$refs.elFormRef.resetFields()
        this.$refs.fileUploadRef.clearFiles()
        this.$refs.upload.clearFiles()
      })
    },

    async init() {
      try {
        this.loading = true
        await this.sleep(400)
        await this.getCourseProfileList()
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },

    async getCourseProfileList() {
      try {
        const res = await getCourseProfile({ course_id: this.courseId })
        console.log('res --------->', res)
        this.list = res.data
      } catch (error) {
        this.$message.error('课程资料获取失败')
      }
    },

    sleep(t) {
      return new Promise((r) => setTimeout(r, t))
    },

    download(row) {
      window.open(row.file)
    },

    uploadSuccess(e, filed) {
      this.form[filed] = e.data.path
    },

    async addFileToCourse() {
      this.$refs.elFormRef.validate(async (valid)=>{
        if (valid) {
          try {
          const res = await addFileToCourse({ ...this.form, course_id: this.courseId })
          console.log('res --------->', res)
          this.$message.success('上传课程资料成功')
          this.refresh(true)
        } catch (error) {
          this.$message.error('上传课程资料失败')
        }
        } else {
          this.$message.error('请填写必填数据')
        }
      })
      // console.log(this.courseId,'this.courseId');
      
    },

    deleteFile(row) {
      this.$confirm('是否删除选中的附件', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = null
        if (!isArray(row)) {
          params = JSON.stringify([row.id])
        } else {
          params = JSON.stringify(row)
        }
        this.deleteFileToCourse(params)
      })
    },

    handleSelectionChange(e) {
      this.current = e.map(item => item.id)
    },

    clearSelection() {
      this.$refs.elTableRef.clearSelection()
    },

    batchDelete() {
      this.deleteFile(this.current)
    },

    async deleteFileToCourse(ids) {
      try {
        const res = await deleteFileToCourse({ ids })
        if (res.code === 200) {
          this.$message.success('删除成功')
        }
        this.clearSelection()
        this.refresh()
      } catch (error) {
        this.$message.error('删除失败')
      }
    },

    refresh(close = false) {
      if (close) this.visible = false
      this.init()
    }
  }
}
</script>
<style lang="scss" scoped>
.course-profile {

  &__header {
    margin: 10px 0;
  }

  .image-slot {
    width: 50px;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #e7e7e7;
  }
}

:deep(.avatar-uploader) {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}

</style>
